﻿using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;

namespace YanZhiwei.DotNet3._5.Utilities.Common
{
    /// <summary>
    /// Db 帮助类
    /// </summary>
    public static class DBHelper
    {
        #region 创建JqGrid的Json
        /// <summary>
        /// 创建JqGrid的Json
        /// </summary>
        /// <param name="excuteResult">DataTable</param>
        /// <returns>Json</returns>
        public static string BuilderJqGridJson(DataTable excuteResult)
        {
            string _json = string.Empty;
            if (excuteResult != null)
            {
                IList<object> _rowObjects = new List<object>();
                int _pageSize = 10;// 每页显示记录数
                int _rowCount = excuteResult.Rows.Count;// 记录总数
                int _columnCount = excuteResult.Columns.Count;// 列数
                int _pageCount = _rowCount % _pageSize == 0 ? _rowCount / _pageSize : _rowCount / _pageSize + 1; // 总页数
                int _ID = 1;
                foreach (DataRow dr in excuteResult.Rows)
                {
                    var _cellValue = new string[_columnCount];
                    for (var i = 0; i < _cellValue.Length; i++)
                    {
                        _cellValue[i] = dr[i].ToString();
                    }
                    var _rowObj = new
                    {
                        id = _ID,
                        cell = _cellValue
                    };
                    _rowObjects.Add(_rowObj);
                    _ID++;
                }
                var _resultObj = new
                {
                    total = _pageCount,    // 总页数
                    page = 1,             // 由于客户端是loadonce的，page也可以不指定
                    records = _rowCount,   // 总记录数
                    rows = _rowObjects     // 数据
                };
                JavaScriptSerializer _serializer = new JavaScriptSerializer();
                _json = _serializer.Serialize(_resultObj);
            }
            return _json;
        }
        #endregion 

    }
}
